package net.retorx

import collection.Map
import java.util.Date
import java.io.File
import org.apache.commons.collections.CollectionUtils
import java.util

class ImageContent(val directory: File,
                   val name: String,
                   val order: Int,
                   val date: Date,
                   var properties: Map[String, String],
                   imageFile: ImageFile,
                   altImageFiles: Iterable[ImageFile])
		extends Content with Ordered[ImageContent] {

    private val nameToAltImageFiles: scala.collection.mutable.Map[String, ImageFile] = scala.collection.mutable.Map()
    addAltImageFiles(altImageFiles)

	private def addAltImageFiles(altImageFiles: Iterable[ImageFile]) {
		for (altImageFile <- altImageFiles) {
			this.nameToAltImageFiles(altImageFile.getName) = altImageFile
		}
	}

    def isHidden = {
        properties.get("hidden") match {
            case Some(hidden) => hidden.toBoolean
            case None => false
        }
    }

    def setProperties(map: Map[String, String]) {
        properties = map
    }

	def getProperties = properties

    def replaceTag(existingTag: String, newTag: String) {
        val tags = this.getTags.transform(tag => {
            if (tag.equals(existingTag)) {
                newTag
            } else {
                tag
            }
        })
        val tagsString = tags.mkString(",")
        properties = properties + ("tags" -> tagsString)
    }

	def getTags = {
		var tags = Array.empty[String]
        properties.get("tags") match {
            case tagsOpt:Some[String] => {
                tags = tagsOpt.get.split(",")
            }
            case None => {
                tags = Array("uncategorized")
            }
        }
		tags
	}

	def getImageFile = { imageFile }

	def getAltImageFile(name: String): ImageFile = {
		nameToAltImageFiles(name)
	}

	def getAllAltImageFiles = {
		nameToAltImageFiles.values
	}

	def sortByDate(that: ImageContent) = {
		date.compareTo(that.date) > 0
	}

	def compare(that: ImageContent) = {
		val sort = order.compare(that.order)
		if (sort != 0) {
			sort
		} else {
			date.compareTo(that.date)
		}
	}

	override def toString = {
		name + " from " + date
	}
}

